<template>
  <div class="article-list">
    <van-pull-refresh 
    v-model="isreFreshLoading" 
    @refresh="onRefresh"
    :success-text="refreshSuccessText"
    :success-duration="1500"

    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
        >
        <article-item 
        v-for="(article,index) in list"
         :key="index"
         :article="article"
        />
     <!-- <van-cell v-for="(article,index) in list" :key="index" :title="article.title" /> -->
      </van-list>
   </van-pull-refresh>
    
  </div>
</template>

<script>
import {getArticles} from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  name:'article-list',
  components:{
    ArticleItem
  },
  data() {
    return {
        list: [],
        loading: false,
        finished: false,
        timestamp: null ,//
        error: false,
        isreFreshLoading:false,
        refreshSuccessText:'刷新成功'
    }
  },    
  props:{
    channels:{
        type: Object,
        required:true

    }
  },
   methods: {
   async onLoad() {
    try {
      const {data } = await getArticles({
        channel_id:this.channels.id,
        timestamp:this.timestamp || Date.now()
      })
      // if(Math.random()>0.5){
      //   JSON.parse('dsnajndjsa')
      // }
    //   console.log(data);
       //2.把请求结果数据放到list中
       const { results } = data.data
       this.list.push(...results)
       //本次数据加载结束之后要把加载状态设置为 结束
       this.loading = false
       //判断数据是否完全被加载
       if (results.length) {
        this.timestamp = data.data.pre_timestamp
       } else {
        this.finished = true
       }
    }catch(err){
      //展示错误提示状态
     this.error = true
     //请求失败了
     this.loading = false
    }
     
  },
  //当下拉触发的时候会执行
  async onRefresh(){
    try {
      const {data } = await getArticles({
        channel_id:this.channels.id,
        timestamp: Date.now()
      })
      // if(Math.random()>0.5){
      //   JSON.parse('dsnajndjsa')
      // }
      //拿到数据 将数据追加到list前面
      const {results} = data.data
       this.list.unshift(...results)

      this.isreFreshLoading = false
      //更新下拉刷新成功的提示文本
      this.refreshSuccessText = `刷新成功 更新了${results.length}条数据`
    }catch(err){
       this.refreshSuccessText = '刷新失败，请重试'
       this.isreFreshLoading = false
    }
  }
}
}
</script>

<style scoped lang="less">
.article-list{
  height: 79vh;
  overflow-y: auto;
}
</style>